#include "comm.hpp"

// 管理管道文件
int main()
{
    // 创建管道 mkfifo
    int n = mkfifo(FIFO_FILE, MODE);
    if(n == -1)
    {
        perror("mkfifo");
        exit(FIFO_CREATE_ERR);
    }

    // 打开管道
    int fd = open(FIFO_FILE, O_RDONLY);
    if(fd < 0)
    {
        perror("open");
        exit(FIFO_OPEN_ERR);
    }

    cout << "server open file done" << endl;
    // 开始通信
    while (true)
    {
        char buffer[1024] = {0};
        int x = read(fd, buffer, sizeof(buffer));
        if(x > 0)
        {
            buffer[x] = 0;
            cout << "client say# " << buffer << endl;
        }
        else if(x == 0)
        {
            cout << "client quit, me too!" << endl;
            break;
        }
        else 
            break;
    }
    close(fd);      // 关闭管道文件    

    // 关闭信道
    int m = unlink(FIFO_FILE);
    if(m == -1)
    {
        perror("unlink");
        exit(FIFO_DELETE_ERR);
    }

    return 0;
}